//
//  HomeTableViewController.swift
//  微博
//
//  Created by mac on 15/12/12.
//  Copyright © 2015年 itcats. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

private let HomeCell = "HomeCell"

class HomeTableViewController: baseTableViewController {
    private lazy var statuses = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin{
        visitorLoginView?.setupInfo("登录后，别人评论你的微博，发给你的消息，都会在这里收到通知", imageName: nil)
            return
        }
        //设置tableView
        prepareTableView()
        
        loadData()
    }
    private func prepareTableView() {
    //注册cell
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: HomeCell)
    }
    
  private func loadData() {
        //实现网络请求
        let AFN = AFHTTPSessionManager()
        //get请求
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
       //判断touken是否为空
    guard let token = UserAccountViewModel().token else{
        print("空")
        SVProgressHUD.showInfoWithStatus("请重新登录")
    return
    }
    let parameters = ["access_token" : token]
        AFN.GET(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            }, success: { (task, result) -> Void in
                //需要判断result 能否转化为字典
                guard let dict = result as? [String : AnyObject] else {
                SVProgressHUD.showInfoWithStatus("你的网路出错,请稍后再试")
                    return
                }
                    //数据获取成功
                    if let array = dict["statuses"] as? [[String : AnyObject]]{
                    print(array)
                        //遍历数组中所有的字典 做字典转模型的操作
                        var list = [Status]()
                        for item in array {
                            let s = Status(dict: item)
                            list.append(s)
                        }
                self.statuses = list
                        //刷新表视图
                        self.tableView.reloadData()
                    
                }
            
            }) { (task, error) -> Void in
                print(error)
        }
    }
    
}
extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCell, forIndexPath: indexPath)
        cell.textLabel?.text = statuses[indexPath.row].text
        return cell
    }
    
}
